import numpy as np
import cv2 as cv
from python_ai.common.xcommon import *

path = '../../../../large_data/pic/Lenna_.png'
img = cv.imread(path, cv.IMREAD_GRAYSCALE)
print("img", img.shape)  # (512, 512)
cv.imshow("img", img)

k = 10
u, s, v = np.linalg.svd(img)
v2 = v[:k, :]  # (k, 512)
p = v2.T  # (512, k)

z = np.matmul(img, p)  # (512, 512)@(512, k) = (512, k)
print_numpy_ndarray_info(z, 'z')
print('z:', z.shape)
z_show = z.copy()
cv.normalize(z_show, z_show, 0, 255, cv.NORM_MINMAX)
z_show = np.uint8(z_show)
print_numpy_ndarray_info(z_show, 'z_show')
cv.imshow('compressed', z_show)

img2 = np.matmul(z, p.T)  # (512, k)@(k, 512) = (512, 512)
print_numpy_ndarray_info(img2, 'img2')
img2 = np.uint8(img2)
cv.imshow('restored', img2)

cv.waitKey(0)
cv.destroyAllWindows()
